Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
Javascript regex (x|y) - ¿Se puede especificar mediante array.join('|')?

Estoy tratando de analizar el texto obtenido de la API de Wikipedia.

En detalle, estoy tratando de analizar el wikitexto de una página wiki completa en secciones separadas. En wikipedia, las secciones están divididas por títulos entre 2 y 5 símbolos iguales (p. ej. == TÍTULO ==). Entonces, todo el wikitexto de una página tiene un montón de esto, y estaba pensando que podría obtener el contenido de cada sección usando split() y regex. Aquí está mi intento ingenuo:

 let wikitext = text; // Obtained from the API let sectiontitles = [sectiontitle1, sectiontitle2...]; // Obtained from the API let sectionsPiped = sectiontitles.join('|'); let regex = new RegExp(`\\={2,5}\\s*(${sectionsPiped})\\s*\\={2,5}`, 'g'); console.log(wikitext.split(regex));

Esto funcionó, pero no de la manera que esperaba. Digamos que el wikitexto tiene el siguiente contorno (reemplazando \n con saltos de línea reales para mejorar la legibilidad):

 == Section 1 == SECTION-1-TEXT === Section 1.1 === SECTION-1.1-TEXT === Section 1.2 === SECTION-1.2-TEXT

Entonces el código anterior devuelve:

 0: '' 1: 'Section 1' 2: 'SECTION-1-TEXT' 3: 'Section 1.1' 4: 'SECTION-1.1-TEXT' 5: 'Section 1.2' 6: 'SECTION-1.2-TEXT'

pero esperaba:

 0: '' 1: 'SECTION-1-TEXT' 2: 'SECTION-1.1-TEXT' 3: 'SECTION-1.2-TEXT'

Supongo que estoy haciendo algo mal con la expresión regular (x|y), así que necesito su ayuda con esto.

Tenga en cuenta que API:Parsing_wikitext puede analizar una sola sección, pero no varias secciones (por este motivo, tendría que iterar las solicitudes de API si intento hacer esto con la API, pero quiero evitarlo porque, de lo contrario, el código será lento ). Y al final, necesito obtener una matriz de los contenidos de cada sección, INCLUYENDO los encabezados de los títulos, así:

 0: '' 1: '== Section 1 ==\nSECTION-1-TEXT' 2: '=== Section 1.1 ===\nSECTION-1.1-TEXT' 3: '=== Section 1.2 ===\nSECTION-1.2-TEXT'

Puedo hacer esto agregando los encabezados a la penúltima matriz anterior después de dividir todo el wikitexto, pero ¿hay alguna forma más fácil de hacerlo? Cualquier ayuda sería apreciada.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!